package org.bud.boot.io.bit;

import org.bud.excel.expot.bit.ExportAskBody;
import org.bud.excel.expot.reply.POIExport;
import org.bud.util.bit.Funcs;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author shaun
 * @date 2024/7/19
 * @instruction
 */
public abstract class Streams {
    public static ResponseEntity<StreamingResponseBody> stream(
            String file, ExportAskBody<?,?>... body){
        POIExport excel = POIExport.XLS;
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        String.format("attachment; filename=%s",
                                new String(file.getBytes(StandardCharsets.UTF_8),
                                        StandardCharsets.ISO_8859_1)))
                .header(HttpHeaders.CONTENT_TYPE, excel.contentType())
                .body(outputStream -> excel.exportExcel(outputStream,body));
    }

    public static void stream(
            HttpServletResponse response,String file,ExportAskBody<?,?>... body){
        POIExport excel = POIExport.XLS;
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s",
                        new String(file.getBytes(StandardCharsets.UTF_8),
                                StandardCharsets.ISO_8859_1)));
        response.addHeader(HttpHeaders.CONTENT_TYPE, excel.contentType());
        Funcs.doOrThrow(b -> excel.exportExcel(response.getOutputStream(),b),body);;
    }
}
